<template>
  <el-dialog
    title="增加文件资源"
    :visible.sync="visible"
    width="460px"
  >
    <el-form
      ref="form"
      :model="form" 
      label-width="80px"
      style="width: 400px;"
    >
      <el-form-item label="类别">
        {{parentCategory.name}}
      </el-form-item>
      <el-form-item prop="title" label="标题" :rules="[{required: true, message: ' '}]">
        <el-input v-model.trim="form.title" autofocus></el-input>
      </el-form-item>
      <el-form-item label="文件" :rules="[{required: true}]">
        <el-upload
          ref="upload"
          action="/api/util/upload"
          :auto-upload="false"
          :limit="1"
          :on-success="onSuccess"
        >
          <el-button slot="trigger" type="primary" plain>选取文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>

    <span slot="footer">
      <el-button type="primary" @click="onSubmit" :loading="submitting">提交</el-button>
      <el-button type="default" @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</template>


<script>
export default {
  data() {
    return {
      visible: false,
      form: {
        categoryId: null,
        resourceType: 1,
        title: '',
        content: ''
      },
      parentCategory: {},
      submitting: false
    };
  },
  methods: {
    show(options) {
      this.visible = true;
      this.submitting = false;
      this.options = options;
      this.parentCategory = options.parentCategory;
      this.form.categoryId = options.parentCategory.id;
      this.form.title = '';
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },
    onChange(file) {
      this.file = file;
    },
    onSubmit() {
      this.submitting = true;
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;
        this.$refs.upload.submit();
      });
    },
    async onSuccess(response) {
      this.submitting = false;
      if (response.success) {
        this.form.url = response.data.url;
        this.form.content = response.data.originalFilename;
        const ret = await this.$http.post('/api/kbase/resource', this.form);
        this.submitting = false;
        if (ret.success) {
          this.$message.success('增加成功');
          this.visible = false;
          this.$refs.upload.clearFiles();
          this.options.onSuccess(data);
        }
      } else {
        this.$message.error(response.message);
      }
    }
  }
}
</script>
